package com.lfg.leetcode.leetcode100;


import java.util.*;

public class No139wordBreak {

    public static void main(String[] args) {
//        boolean ret = wordBreak("applepenapple", new ArrayList<String>(Arrays.asList("apple,pen".split(","))));
        boolean ret = wordBreak("catsandog", new ArrayList<String>(Arrays.asList("cats,dog,sand,and,cat".split(","))));
        System.out.println(ret);
    }

    public static boolean wordBreak(String s, List<String> wordDict) {
        if (null == s || null == wordDict || "".equals(s) || wordDict.isEmpty()) {
            return false;
        }

        int length = s.length();
        boolean[] ret = new boolean[length + 1];
        int minLength = length;
        int maxLength = 0;
        for (String str : wordDict) {
            maxLength = Math.max(maxLength, str.length());
            minLength = Math.min(minLength, str.length());
        }
        ret[0] = true;
        Set<String> set = new HashSet<>(wordDict);
        for (int i = 0; i < length; i++) {
            if (!ret[i]) {
                continue;
            }
            int end = i + maxLength;
            for (int endIndex = minLength + i; endIndex <= end && endIndex <= length; endIndex++) {
                if (set.contains(s.substring(i, endIndex))) {
                    ret[endIndex] = true;
                }
            }
            if (ret[length]) {
                return ret[length];
            }
        }

        return ret[length];
    }
}
